package com.imist.controller;

import com.imist.bean.User;
import com.imist.service.ShopService;
import com.imist.utils.Constants;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    //定义业务层对象,这里不可以注入，因为servlet不是由Spring容器进行管理的
    private ShopService shopService;

    @Override
    public void init() throws ServletException {
        super.init();
        //获取Spring容器，然后从容器中获取到业务层对象
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        shopService = (ShopService) context.getBean("shopService");

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method){
            case "getJsp": {
                //跳转到登录界面
                req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
                break;
            }
            case "login":
            {
                login(req,resp);
            }
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String username = req.getParameter("loginName");
            String password = req.getParameter("passWord");
            Map<String ,Object> result =shopService.login(username,password);
        if ((int)result.get("code") == 0){
            User user = (User) result.get("msg");
            req.getSession().setAttribute(Constants.USER_SESSION ,user);
            req.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(req,resp);
        }else {
            String msg = result.get("msg")+"";
            req.setAttribute("msg",msg);
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,resp);
        }
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
